﻿using Ini_Config.Common;
using Ini_Config.CustomControl;
using Microsoft.Win32;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;

namespace Ini_Config
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        private string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configure\\test.ini");
        private string jsonPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configure\\test.json");
        private string? IniPath;
        private string? ConfigString;
        private string? GetMachineString;
        private ListsAndGridsViewModel viewModel;
        private string filePath = AppDomain.CurrentDomain.BaseDirectory + "\\output\\";
        public MainWindow()
        {
            viewModel = new ListsAndGridsViewModel();
            DataContext = viewModel;
            InitializeComponent();
            TestWindow.Title = "上位机配置文件配置系统_V1.0";
        }

        private void btn_AddConfig_Click(object sender, RoutedEventArgs e)
        {
            // 使用 viewModel 实例来访问 Items 集合
            var newModel = new SelectableViewModel
            {
                EnName = "",
                ChName = "",
            };

            viewModel.Items.Add(newModel);
        }

        //文件打开初始化
        private void FileIni()
        {
            try
            {
                //读取参数数值
                string[] nodeNames = Fun.GetIniFileNodeNames(IniPath!);

                // 在控制台上显示节点和键值对
                foreach (string nodeName in nodeNames)
                {
                    Debug.WriteLine(nodeName);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //打开参数
        private void btn_OpenPara_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //打开文件并把值显示出来
                OpenFileDialog fileDialog = new OpenFileDialog();
                fileDialog.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory;//Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configure");    //打开对话框后的初始目录
                fileDialog.Filter = "CSV文件|*.csv|所有文件|*.*";
                fileDialog.RestoreDirectory = false;    //若为false，则打开对话框后为上次的目录。若为true，则为初始目录
                if (fileDialog.ShowDialog() == true)
                {
                    IniPath = Path.GetFullPath(fileDialog.FileName);
                    FilePath.Text = IniPath;
                    //FileIni();
                    LoadCsvData();
                    MessageBox.Show("打开成功！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        //保存参数
        private void btn_SavePara_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 导出表格数据到 CSV 文件
                // 清空 CSV 文件的内容
                File.WriteAllText("exported_data.csv", string.Empty);
                StringBuilder csvContent = new StringBuilder();
                csvContent.AppendLine("EnName,ChName,TestType");
                ClearTxt(path);

                List<GridInfo> grids = new List<GridInfo>();
                // 创建示例配置
                GridInfo ParaGrop = new GridInfo() { Name = "ParaGrop" };
                GridInfo PresetValueGrop = new GridInfo() { Name = "PresetValueGrop" };

                string json = "[";
                JObject jsonObject = new JObject();

                foreach (var item in viewModel.Items)
                {
                    List<string> line = new List<string>
                    {
                        "RobotDevice = new Parameter.DeviceRobotInfo();",
                        "RobotDevice.RobotENName = GetMachineString." + item.EnName + ";",
                        "RobotDevice.RobotCHName =\"" + item.ChName + "\";",
                        "RobotDevice.CheckState = false;",
                        //"IsCheck = Fun.ReadSingleFile(\"Ischeck_Item\", GetMachineString." + item.EnName + ", Parameter.IniPath_Item);",
                        //"if (IsCheck.Equals(\"1\"))",
                        //"RobotDevice.IsCheck = true;",
                        "if (keyValues.ContainsKey(GetMachineString." + item.EnName + ")){",
                        "RobotDevice.IsCheck = keyValues[GetMachineString." + item.EnName + "].IsCheck;",
                    };
                    switch (item.TestType.ToString())
                    {
                        case "范围值比较":
                            line.Add("RobotDevice.TestType = (int)Parameter.TestMethod.Range_Compare;");
                            line.Add("RobotDevice.MinValue = keyValues[GetMachineString." + item.EnName + "].Min.ToString();");
                            line.Add("RobotDevice.MaxValue = keyValues[GetMachineString." + item.EnName + "].Max.ToString();");
                            //line.Add("RobotDevice.MinValue = Fun.ReadSingleFile(\"Auto_Test_Reference\", GetMachineString." + item.EnName + " + \"_Min\", Parameter.IniPath);");
                            //line.Add("RobotDevice.MaxValue = Fun.ReadSingleFile(\"Auto_Test_Reference\", GetMachineString." + item.EnName + " + \"_Max\", Parameter.IniPath);");
                            //ParaGrop.Rows.Add(new RowInfo() { Label = item.EnName, TextBoxMin = item.EnName + "_Min", TextBoxMax = item.EnName + "_Max" });
                            break;
                        case "相等比较":
                            line.Add("RobotDevice.TestType = (int)Parameter.TestMethod.Equal_Compare;");
                            line.Add("RobotDevice.PresetValue = keyValues[GetMachineString." + item.EnName + "].Perset??\"\".ToString();");
                            //line.Add("RobotDevice.PresetValue = Fun.ReadSingleFile(\"Auto_Test_Reference\", GetMachineString." + item.EnName + " + \"_Set\", Parameter.IniPath);");
                            //PresetValueGrop.Rows.Add(new RowInfo() { Label = item.EnName, TextBoxSet = item.EnName + "_Set" });
                            break;
                        case "二次比较_地检类":
                            line.Add("RobotDevice.TestType = (int)Parameter.TestMethod.Second_Compare_Cliff;");
                            line.Add("RobotDevice.MinValue = keyValues[GetMachineString." + item.EnName + "].Min.ToString();");
                            line.Add("RobotDevice.MaxValue = keyValues[GetMachineString." + item.EnName + "].Max.ToString();");
                            //line.Add("RobotDevice.MinValue = Fun.ReadSingleFile(\"Auto_Test_Reference\", GetMachineString." + item.EnName + " + \"_Min\", Parameter.IniPath);");
                            //line.Add("RobotDevice.MaxValue = Fun.ReadSingleFile(\"Auto_Test_Reference\", GetMachineString." + item.EnName + " + \"_Max\", Parameter.IniPath);");
                            //ParaGrop.Rows.Add(new RowInfo() { Label = item.EnName, TextBoxMin = item.EnName + "_Min", TextBoxMax = item.EnName + "_Max" });
                            break;
                        case "二次比较_堵转类":
                            line.Add("RobotDevice.TestType = (int)Parameter.TestMethod.Second_Compare_Lock;");
                            line.Add("RobotDevice.MinValue = keyValues[GetMachineString." + item.EnName + "].Min.ToString();");
                            line.Add("RobotDevice.MaxValue = keyValues[GetMachineString." + item.EnName + "].Max.ToString();");
                            line.Add("RobotDevice.LockValue = keyValues[GetMachineString." + item.EnName + "].Lock.ToString();");
                            //line.Add("RobotDevice.MinValue = Fun.ReadSingleFile(\"Auto_Test_Reference\", GetMachineString." + item.EnName + " + \"_Min\", Parameter.IniPath);");
                            //line.Add("RobotDevice.MaxValue = Fun.ReadSingleFile(\"Auto_Test_Reference\", GetMachineString." + item.EnName + " + \"_Max\", Parameter.IniPath);");
                            //line.Add("RobotDevice.LockValue = Fun.ReadSingleFile(\"Auto_Test_Reference\", GetMachineString." + item.EnName + " + \"_Lock\", Parameter.IniPath);");
                            //ParaGrop.Rows.Add(new RowInfo() { Label = item.EnName, TextBoxMin = item.EnName + "_Min", TextBoxMax = item.EnName + "_Max", TextBoxLock = item.EnName + "_Lock" });
                            break;
                        case "二次比较_开关量":
                            line.Add("RobotDevice.TestType = (int)Parameter.TestMethod.Second_Compare_OnSide;");
                            break;
                        default:
                            line.Add("RobotDevice.TestType = (int)Parameter.TestMethod.Tbd;");
                            break;
                    }
                    line.Add("}");
                    line.Add("Parameter.SourceDict.Add(RobotDevice.RobotENName, RobotDevice);\r\n");

                    foreach (var lineList in line)
                    {
                        ConfigString += lineList + Environment.NewLine;
                    }
                    GetMachineString += "public static string " + item.EnName + "= \"" + item.EnName + "\";" + Environment.NewLine;
                    Fun.WriteSingleFile("Test_Item", item.EnName!, item.ChName!, path);
                    //  Fun.WriteSingleFile("Ischeck_Item", item.EnName!, "1", IniPath!);

                    csvContent.AppendLine($"{item.EnName},{item.ChName},{item.TestType}"); // 根据你的数据结构修改

                    Setting setting = new Setting { Name = item.EnName, IsCheck = true };
                    if (item == viewModel.Items.LastOrDefault())
                        //json += JsonConvert.SerializeObject(setting,Formatting.Indented);//Formatting.Indented用于在序列化过程中添加换行和缩进
                        json += JsonConvert.SerializeObject(setting) + "]";
                    else
                        json += JsonConvert.SerializeObject(setting) + "," + Environment.NewLine;
                }
                File.WriteAllText(jsonPath, json);

                ClearTxt(filePath + "ConfigString.txt");
                File.AppendAllText(filePath + "ConfigString.txt", ConfigString);

                ClearTxt(filePath + "GetMachineString.txt");
                File.AppendAllText(filePath + "GetMachineString.txt", GetMachineString);



                grids.Add(ParaGrop);
                grids.Add(PresetValueGrop);
                WriteConfig(grids);

                File.WriteAllText(filePath + "exported_data.csv", csvContent.ToString(), Encoding.UTF8);
                MessageBox.Show("保存成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //将txt内容清空
        public void ClearTxt(string txtPath)
        {
            FileStream stream = File.Open(txtPath, FileMode.OpenOrCreate, FileAccess.Write);
            stream.Seek(0, SeekOrigin.Begin);
            stream.SetLength(0);
            stream.Close();
        }
        private void WriteConfig(List<GridInfo> grids)
        {
            foreach (GridInfo grid in grids)
            {
                foreach (RowInfo row in grid.Rows)
                {
                    if (!string.IsNullOrEmpty(row.Label))
                        Fun.WriteSingleFile(row.Label + "_" + grid.Name!, "Label", row.Label, path);
                    if (!string.IsNullOrEmpty(row.TextBoxMin))
                        Fun.WriteSingleFile(row.Label + "_" + grid.Name!, "TextBox_Min", row.TextBoxMin, path);
                    if (!string.IsNullOrEmpty(row.TextBoxMax))
                        Fun.WriteSingleFile(row.Label + "_" + grid.Name!, "TextBox_Max", row.TextBoxMax, path);
                    if (!string.IsNullOrEmpty(row.TextBoxLock))
                        Fun.WriteSingleFile(row.Label + "_" + grid.Name!, "TextBox_Lock", row.TextBoxLock, path);
                    if (!string.IsNullOrEmpty(row.TextBoxSet))
                        Fun.WriteSingleFile(row.Label + "_" + grid.Name!, "TextBox_Set", row.TextBoxSet, path);
                }

            }
        }
        class GridInfo
        {
            public string? Name { get; set; }
            public List<RowInfo> Rows { get; } = new List<RowInfo>();
        }


        class RowInfo
        {
            public string? Label { get; set; }
            public string? TextBoxMin { get; set; }
            public string? TextBoxMax { get; set; }
            public string? TextBoxLock { get; set; }
            public string? TextBoxSet { get; set; }
        }

        class Setting
        {
            public string? Name { get; set; }
            public bool IsCheck { get; set; }
            public float? Min { get; set; }
            public float? Max { get; set; }
            public float? Lock { get; set; }
            public string? Perset { get; set; }
        }
        //读取 CSV 文件
        private void LoadCsvData()
        {
            // 读取 CSV 文件的内容
            string[] csvLines = File.ReadAllLines(filePath + "exported_data.csv");

            // 遍历每一行并将其转换为 CsvData 对象
            foreach (string line in csvLines.Skip(1)) // 跳过标题行
            {
                string[] columns = line.Split(',');
                if (columns.Length >= 3) // 根据列数调整
                {
                    var newModel = new SelectableViewModel
                    {
                        EnName = columns[0],
                        ChName = columns[1],
                    };
                    switch (columns[2])
                    {
                        case "范围值比较":
                            newModel.TestType = TestType.范围值比较;
                            break;
                        case "相等比较":
                            newModel.TestType = TestType.相等比较;
                            break;
                        case "二次比较_堵转类":
                            newModel.TestType = TestType.二次比较_堵转类;
                            break;
                        case "二次比较_地检类":
                            newModel.TestType = TestType.二次比较_地检类;
                            break;
                        case "二次比较_开关量":
                            newModel.TestType = TestType.二次比较_开关量;
                            break;
                        case "待定":
                            newModel.TestType = TestType.待定;
                            break;
                        default: break;
                    }
                    viewModel.Items.Add(newModel);
                }
            }
        }
    }
}